package jjn.offer_round2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Jiang Jining
 * @since 2023-06-24 23:59
 */
public class Offer38 {
    public String[] permutation(String s) {
        boolean[] visited = new boolean[s.length()];
        List<String> result = new ArrayList<>();
        char[] input = s.toCharArray();
        Arrays.sort(input);
        backtrack(input, visited, new StringBuilder(), result);
        String[] res = new String[result.size()];
        for (int i = 0; i < result.size(); i++) {
            res[i] = result.get(i);
        }
        return res;
    }
    
    private void backtrack(char[] input, boolean[] visited, StringBuilder sb, List<String> result) {
        if (sb.length() == input.length) {
            result.add(sb.toString());
            return;
        }
        for (int i = 0; i < input.length; i++) {
            if (i > 0 && input[i] == input[i - 1] && !visited[i - 1]) {
                continue;
            }
            if (!visited[i]) {
                sb.append(input[i]);
                visited[i] = true;
                backtrack(input, visited, sb, result);
                visited[i] = false;
                sb.deleteCharAt(sb.length() - 1);
            }
        }
    }
    
    public static void main(String[] args) {
        String[] permutationTest1 = new Offer38().permutation("abc");
        System.out.println("permutationTest1 = " + Arrays.toString(permutationTest1));
        String[] permutationTest2 = new Offer38().permutation("aba");
        System.out.println("permutationTest2 = " + Arrays.toString(permutationTest2));
    }
}
